<template>
  <view class="pt4 px-2 publish h-full">
    <wd-message-box />
    <wd-toast />
    <view class="form">
      <form @submit="formSubmit">
        <wd-cell-group custom-class="group" title="基础信息" border>
          <wd-calendar v-model="formData.COL_0.value" label="加油日期" />
          <wd-picker required :columns="xiangmuList" label="项目名称" value-key="COL_4" label-key="COL_3" v-model="formData.COL_9.value" />
          <wd-picker
            :disabled="!formData.COL_9.value"
            required
            :columns="kehuList"
            value-key="COL_1"
            label-key="COL_1"
            label="客户名称"
            v-model="formData.COL_8.value"
            @confirm="kehuChange"
          />
          <wd-picker
            :disabled="!formData.COL_9.value"
            required
            :columns="columns"
            value-key="COL_4"
            label-key="COL_4"
            label="油品名称"
            v-model="formData.COL_1.value"
          />
          <wd-picker
            :disabled="!formData.COL_9.value"
            required
            :columns="oilModelList"
            value-key="COL_5"
            label-key="COL_5"
            label="油品型号"
            v-model="formData.COL_2.value"
          />
          <wd-input type="digit" label="加油数量" placeholder="请输入提油数量" required v-model="formData.COL_3.value" />
        </wd-cell-group>
        <wd-cell title="加油单位" title-width="90px" required>
          <wd-radio-group v-model="formData.unit_type.value" size="small" shape="button" inline>
            <wd-radio value="吨">吨</wd-radio>
            <wd-radio value="升">升</wd-radio>
          </wd-radio-group>
        </wd-cell>
        <wd-cell-group title="票据上传" border class="p3">
          <view class="h-10"></view>
          <wd-upload
            multiple
            :file-list="fileList"
            :header="{
              'Blade-Auth': token
            }"
            action="https://miniappnew.zhangmushiye.com/api/file/uploadFile/record"
            @change="handleChange"
          ></wd-upload>
        </wd-cell-group>
        <!--        密度：{{ formData.other.COL_6 }} 吨数：{{ total.ton }} 单价：{{ formData.other.COL_7 }} 金额：{{ total.price }}-->
        <view class="text-center p3">
          <wd-button block type="success" @click="formSubmit">提交</wd-button>
        </view>
      </form>
    </view>
  </view>
</template>

<script setup>
import dayjs from 'dayjs'
import { useMessage, useToast } from 'wot-design-uni'
import { ref } from 'vue'
import DemoApi from '@/api/DemoApi'
import { token } from '@/pages/user'

const { userInfo } = storeToRefs(useAuthStore())

const toast = useToast()
const messageBox = useMessage()
// '{"48":1720022400000,"49":"柴油","50":"0#","51":1,"52":0.83,"53":"0.001","54":10,"55":10,"56":"广西全灌高速","57":"P132","58":"广西全灌高速","59":"王如梦","60":"余威","63":"王如梦","64":"13167505967","65":"","66":"","67":"","69":"0","70":"升"}'

// "{"48":1720022400000,"49":"柴油","50":"0#","51":"6024.096","52":"0.8300","53":"5","54":0,"55":"0.000","56":"广西全灌高速","57":"P132","58":"广西全灌高速","59":"王如梦","60":"余威","61":116.24499,"62":39.94969,"63":"18610028518","64":"13167505967","65":1720069858906,"66":1720069858906,"67":["1808730259049226241"],"69":"0","70":"吨"}"
const defaultFormData = {
  COL_0: {
    field: 'COL_0',
    fieldId: 48,
    fieldName: '加油日期',
    dataType: 'DATETIME',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: dayjs().format('YYYY-MM-DD')
  },
  COL_3: {
    field: 'COL_3',
    fieldId: 51,
    fieldName: '数量升',
    dataType: 'NUMBER',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_1: {
    field: 'COL_1',
    fieldId: 49,
    fieldName: '油品名称',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_4: {
    field: 'COL_4',
    fieldId: 52,
    fieldName: '油品密度',
    dataType: 'NUMBER',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_2: {
    field: 'COL_2',
    fieldId: 50,
    fieldName: '油品型号',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_5: {
    field: 'COL_5',
    fieldId: 53,
    fieldName: '折算吨',
    dataType: 'NUMBER',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_6: {
    field: 'COL_6',
    fieldId: 54,
    fieldName: '送油单价',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_7: {
    field: 'COL_7',
    fieldId: 55,
    fieldName: '送油金额',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_8: {
    field: 'COL_8',
    fieldId: 56,
    fieldName: '客户名称',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_9: {
    field: 'COL_9',
    fieldId: 57,
    fieldName: '项目编号',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_10: {
    field: 'COL_10',
    fieldId: 58,
    fieldName: '项目名称',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_11: {
    field: 'COL_11',
    fieldId: 59,
    fieldName: '司机名称',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: userInfo.value.name
  },
  COL_12: {
    field: 'COL_12',
    fieldId: 60,
    fieldName: '队长名称',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: userInfo.value.COL_5
  },
  COL_13: {
    field: 'COL_13',
    fieldId: 61,
    fieldName: '经度',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_14: {
    field: 'COL_14',
    fieldId: 62,
    fieldName: '维度',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_15: {
    field: 'COL_15',
    fieldId: 63,
    fieldName: '司机手机号码',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: userInfo.value.COL_1
  },
  COL_16: {
    field: 'COL_16',
    fieldId: 64,
    fieldName: '队长手机号码',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: ''
  },
  COL_17: {
    field: 'COL_17',
    fieldId: 65,
    fieldName: '提交日期',
    dataType: 'DATETIME',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: dayjs().valueOf()
  },
  COL_18: {
    field: 'COL_18',
    fieldId: 66,
    fieldName: '最后修改日期',
    dataType: 'DATETIME',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: dayjs().valueOf()
  },
  COL_19: {
    field: 'COL_19',
    fieldId: 67,
    fieldName: '加油单据',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ODS_Oildelivery',
    value: []
  },
  unit_type: {
    field: 'unit_type',
    fieldId: 70,
    fieldName: '单位吨或者升',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ods_oildelivery',
    value: '升'
  },
  settlement_type: {
    field: 'settlement_type',
    fieldId: 69,
    fieldName: '结算状态',
    dataType: 'STRING',
    tableAliasName: 'GsjST',
    tableName: 'ods_oildelivery',
    value: '0'
  }
}
const formData = ref(defaultFormData)

let id = ''
onLoad(async (options) => {
  if (options.query) {
    console.log(options.query)
    // 正在加载
    toast.loading({ loadingType: 'ring', msg: '加载中' })
    const item = JSON.parse(decodeURIComponent(options.query))
    fileList.value = item.COL_19.map((item) => {
      return {
        name: item,
        url: 'https://miniappnew.zhangmushiye.com/api/file/getFileInputStreamById/' + item
      }
    })
    id = item.ID
    await uni.request({
      url: 'https://miniappnew.zhangmushiye.com/bi-api/report/dataapi/driverXiangmu',
      method: 'GET',
      data: {
        phone: userInfo.value.COL_1
      },
      success: (res) => {
        xiangmuList.value = res.data.data
      }
    })
    await DemoApi.projectList(userInfo.value).then((res) => {
      oldColumns.value = res.data
      // 排重
      columns.value = res.data.filter((item, index, arr) => {
        return arr.findIndex((item2) => item2.COL_1 == item.COL_1) == index
      })
      oilList.value = res.data.filter((item, index, arr) => {
        return arr.findIndex((item2) => item2.COL_5 == item.COL_5) == index
      })
      Object.values(formData.value).forEach((item2) => {
        item2.value = item[item2.field]
      })
      toast.close()
    })
  } else {
    await uni.request({
      url: 'https://miniappnew.zhangmushiye.com/bi-api/report/dataapi/driverXiangmu',
      method: 'GET',
      data: {
        phone: userInfo.value.COL_1
      },
      success: (res) => {
        xiangmuList.value = res.data.data
      }
    })

    // DemoApi.projectList(userInfo.value).then((res) => {
    //   oldColumns.value = res.data
    //   // 排重
    //   columns.value = res.data.filter((item, index, arr) => {
    //     return arr.findIndex((item2) => item2.COL_1 === item.COL_1) === index
    //   })
    //   oilList.value = res.data.filter((item, index, arr) => {
    //     return arr.findIndex((item2) => item2.COL_5 === item.COL_5) === index
    //   })
    //   toast.close()
    // })
  }
})

const formSubmit = () => {
  if (!formData.value.COL_9.value) {
    toast.show('请选择项目名称')
    return
  }
  if (!formData.value.COL_8.value) {
    toast.show('请选择客户名称')
    return
  }
  if (!formData.value.COL_3.value) {
    toast.show('请输入加油数量')
    return
  }
  // 单位
  if (!formData.value.unit_type.value) {
    toast.show('请选择单位')
    return
  }
  if (!formData.value.COL_19.value) {
    toast.show('请上传加油票据')
    return
  }

  const find = oldColumns.value.find(
    (item) => item.COL_0 == formData.value.COL_9.value && item.COL_4 == formData.value.COL_1.value && item.COL_5 == formData.value.COL_2.value
  )
  if (!find) {
    return false
  }
  // 油品密度
  formData.value.COL_4.value = find.COL_6
  // 吨数
  let ton = 0
  if (find.jiesuandanwei == '吨') {
    // 加油单价
    formData.value.COL_6.value = find.COL_7 || 0
    if (formData.value.unit_type.value == '吨') {
      // 吨数量
      // formData.value.COL_5.value = +formData.value.COL_3.value || 0
      // 升数量
      formData.value.COL_5.value = ((formData.value.COL_3.value / formData.value.COL_4.value) * 1000).toFixed(3)
      // 加油金额
      formData.value.COL_7.value = (formData.value.COL_3.value * formData.value.COL_6.value).toFixed(3)
    }
    if (formData.value.unit_type.value == '升') {
      // 升数量
      // formData.value.COL_3.value = +formData.value.COL_3.value || 0
      // 吨数量
      formData.value.COL_5.value = ((formData.value.COL_3.value * formData.value.COL_4.value) / 1000).toFixed(3)
      // 加油金额
      formData.value.COL_7.value = ((formData.value.COL_6.value * formData.value.COL_3.value * formData.value.COL_4.value) / 1000).toFixed(3)
    }
  }

  if (find.jiesuandanwei == '升') {
    // 加油单价
    formData.value.COL_6.value = find.unitprice_s || 0
    if (formData.value.unit_type.value == '吨') {
      // 吨数量
      // formData.value.COL_5.value = +formData.value.COL_3.value || 0
      // 升数量
      formData.value.COL_5.value = ((formData.value.COL_3.value / formData.value.COL_4.value) * 1000).toFixed(3)
      // 加油金额
      formData.value.COL_7.value = (((formData.value.COL_6.value * formData.value.COL_3.value) / formData.value.COL_4.value) * 1000).toFixed(3)
    }
    if (formData.value.unit_type.value == '升') {
      // 升数量
      // formData.value.COL_3.value = +formData.value.COL_3.value || 0
      // 吨数量
      formData.value.COL_5.value = ((formData.value.COL_3.value * formData.value.COL_4.value) / 1000).toFixed(3)
      // 加油金额
      formData.value.COL_7.value = (formData.value.COL_3.value * formData.value.COL_6.value).toFixed(3)
    }
  }
  // 项目编号
  // formData.value.COL_9.value = find.COL_0
  // 项目名称
  formData.value.COL_10.value = xiangmuList.value.find((item) => item.COL_4 == formData.value.COL_9.value).COL_3
  console.log('formData', formData.value)
  // return false
  let params = {}
  Object.values(formData.value).forEach((item) => {
    params[item.fieldId] = item.value
  })
  params[48] = dayjs(params[48]).valueOf()
  if (id) {
    params[65] = dayjs(params[65]).valueOf()
    params[66] = dayjs().valueOf()
  }
  let val = ''
  params[67].forEach((v) => {
    val += v + ';'
  })
  params[67] = val.substring(0, val.length - 1)
  if (params[70] == '吨') {
    const paramsh = JSON.parse(JSON.stringify(params))
    params[53] = paramsh['51']
    params[51] = paramsh['53']
  }
  params = JSON.stringify(params)
  messageBox
    .confirm({
      title: '提示',
      msg: '确认提交吗？'
    })
    .then(() => {
      toast.loading({ loadingType: 'ring', msg: '提交中' })
      let url = 'https://miniappnew.zhangmushiye.com/visual-api/paas/visualdev/data/Base/v3'
      if (id) {
        url = url + '/primary/6b17000a60a0457ecd2a73baa119c011/' + id + '/7'
        // PUT 提交
        uni.request({
          url,
          method: 'PUT',
          header: {
            'Blade-Auth': token.value
          },
          data: {
            primaryTable: {
              dbLink: '7',
              id: id,
              oldData: null,
              data: params
            },
            foreignTable: []
          },
          success: (res) => {
            toast.success('提交成功')
            uni.navigateBack()
          },
          fail: (err) => {
            toast.error('提交失败')
          }
        })
      } else {
        url = url + '/6b17000a60a0457ecd2a73baa119c011'
        uni.request({
          url,
          method: 'POST',
          header: {
            'Blade-Auth': token.value
          },
          data: {
            primaryTable: {
              dbLink: '7',
              id: '',
              oldData: null,
              data: params
            },
            foreignTable: []
          },
          success: (res) => {
            toast.success('提交成功')
            uni.navigateBack()
          },
          fail: (err) => {
            toast.error('提交失败')
          }
        })
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

// 获取gps
uni.getFuzzyLocation({
  type: 'gcj02',
  success: function (res) {
    console.log(res)
    formData.value.COL_13.value = res.longitude
    formData.value.COL_14.value = res.latitude
  }
})

const fileList = ref([])
function handleChange(files) {
  let file = []
  files.fileList.forEach((item) => {
    file.push(item)
  })
  console.log(file)
  formData.value.COL_19.value = file.map((item) => {
    let res = {}
    try {
      res = JSON.parse(item.response)
    } catch (e) {
      res = item.response
    }
    if (!item.response) {
      res = {
        data: {
          id: item.name
        }
      }
    }
    return res.data.id
  })
}

// 项目列表
const oldColumns = ref([])
const columns = ref([])
const xiangmuList = ref([])
// 油品列表
const oilList = ref([])

// 客户列表
const kehuList = ref([])
watch(
  () => formData.value.COL_9.value,
  (val) => {
    // formData.value.COL_8.value = ''
    // formData.value.COL_1.value = ''
    // formData.value.COL_2.value = ''
    // formData.value.COL_3.value = ''

    uni.request({
      url: 'https://miniappnew.zhangmushiye.com/bi-api/report/dataapi/kehu',
      method: 'GET',
      data: {
        xiangmu_id: val
      },
      success: (res) => {
        kehuList.value = res.data.data

        DemoApi.login({ mobile: userInfo.value.COL_1, name: userInfo.value.name, project_code: val }).then((resp) => {
          // 队长姓名
          formData.value.COL_12.value = resp.data[0].COL_5
          // 队长手机号
          formData.value.COL_16.value = resp.data[0].COL_6
        })
        DemoApi.projectList({ COL_4: val }).then((res) => {
          oldColumns.value = res.data
          columns.value = res.data.filter((item, index, arr) => {
            return arr.findIndex((item2) => item2.COL_1 == item.COL_1) == index
          })
          oilList.value = res.data.filter((item, index, arr) => {
            return arr.findIndex((item2) => item2.COL_5 == item.COL_5) == index
          })
        })
      }
    })
  }
)
const kehuChange = (e) => {
  // formData.value.COL_9.value = e.selectedItems.COL_9
}
// 油品型号
const oilModelList = ref([])
watch(
  () => formData.value.COL_1.value,
  (val) => {
    oilModelList.value = oilList.value.filter((item) => item.COL_4 == val)
  }
)
</script>

<style lang="scss">
.publish {
  background-image: url('https://pic.imgdb.cn/item/65597b6dc458853aef74938b.png');

  .form {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    margin-top: 20px;
  }
}
</style>
